#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stdint.h>

#include "debug.h"
#include "os_api.h"
#include "ps_api.h"
#include "dev_api.h"
#include "mqttclient.h"
#include "os_api.h"
#include "debug.h"
#include "hal/gpio.h"
#include "lpconfig.h"

extern void atcmds_register_init(void);

extern void lqgpio_main(void);
extern void lqtcp_main(void);
extern void lqmqtt_main(void);

extern int mqtt_send_msg(uint32_t msgId, void *data);
extern int tcp_send_msg(uint32_t msgId, void *data);

#define LP_WAKEUP_GPIO        4

void lp_gpio_init(void)
{
    GPIOReturnCode status = GPIORC_OK;

    status = hal_GpioSetDir(LP_WAKEUP_GPIO, GPIO_OUT_PIN);
	if (status != GPIORC_OK){
		LOG_PRINTF("status: 0x%lx", status);
	}
}

void lp_wakeup_internal(int wake)
{
    if (wake) {
        // 用于唤醒主控开机，以及连接Vbus物理连接等;
        hal_GpioOut(LP_WAKEUP_GPIO, 1);

        // 禁止模块休眠
        dev_SetSleep(0);
    } else {
        // 用于控制主控关机，以及断开Vbus物理连接等;
        hal_GpioOut(LP_WAKEUP_GPIO, 0); 

        // 允许模块休眠，（还需满足其他条件，模块才会进入低功耗模式，主要是vbus断开，无上下行数据传输，uart无数据输入）
        dev_SetSleep(1);
    }
}

void lp_wakeup(void)
{
    lp_wakeup_internal(1);
}

void lp_sleep(void)
{
    lp_wakeup_internal(0);
}


void lp_cmd_start(void)
{
    lpSetCfg *cfg = getLpCfgInfo();

    if (cfg->method == 0){
        tcp_send_msg(TCP_CMD_START, NULL);
    }else if (cfg->method == 1){
        mqtt_send_msg(MQTT_CMD_START, NULL);
    }
}

void lp_cmd_stop(void)
{
    lpSetCfg *cfg = getLpCfgInfo();

    if (cfg->method == 0){
        tcp_send_msg(TCP_CMD_STOP, NULL);
    }else if (cfg->method == 1){
        mqtt_send_msg(MQTT_CMD_STOP, NULL);
    }
}

void lp_cmd_wakeup(void)
{
    lpSetCfg *cfg = getLpCfgInfo();

    if (cfg->method == 0){
        tcp_send_msg(TCP_CMD_WAKEUP, NULL);
    }else if (cfg->method == 1){
        mqtt_send_msg(MQTT_CMD_WAKEUP, NULL);     
    }
}

void lp_cmd_sleep(void)
{
    lpSetCfg *cfg = getLpCfgInfo();

    if (cfg->method == 0){
        tcp_send_msg(TCP_CMD_SUSPEND, NULL);
    }else if (cfg->method == 1){
        mqtt_send_msg(MQTT_CMD_SLEEP, NULL);
    }
}


int main(void)
{	
	int ret;

    atcmds_register_init();

    lp_gpio_init();

    // 开机的时候，主动触发唤醒主控，主要用于模块异常重启时，唤醒主控重新配置MQTT链接状态
    lp_wakeup();

    lqgpio_main();
    
    lqtcp_main();
    
    lqmqtt_main();
    
	return 0;
}
